﻿using Core.Ndatax.Domain;
using Core.Ndatax.Domain.Dto;
using Core.Ndatax.Infrastructure.Common;
using Xman.Extensions.Core;

namespace Core.Ndatax.Services
{
    public class ESBService : IESBService
    {
        private readonly ILogger<ESBService> _logger;
        private readonly IBllRequest _bllRequest;
        private readonly ResServer _httpClientServer;

        public ESBService(ILogger<ESBService> logger,IBllRequest bllRequest, ResServer httpClientServer)
        {
            _logger= logger;
            _bllRequest= bllRequest;   
            _httpClientServer= httpClientServer;
        }
        public string HIPMessageServer(string message)
        {
            _logger.LogInformation("收到的消息：" + message);
            var error = "";
            var eventValue = "";
            try
            {
                var element = message.ToXElement().WithoutNamespaces();
                eventValue = element.Element("interactionId").GetAttributeValue("extension");
                if (eventValue== HL7Helper.AddRequest)//JH0201
                {
                    _logger.LogInformation("进行的操作是：消息代码--JH0201，新增申请单");
                    var dto = HL7Helper.CreateAddRequestDto(element);
                    _bllRequest.AddRequestAsync(dto).GetAwaiter().GetResult();
                }
                else if(eventValue == HL7Helper.DelRequest)//JH0204
                {
                    _logger.LogInformation("进行的操作是：消息代码--JH0204，作废申请单");
                    var dto = HL7Helper.CreateDelRequestDto(element);
                    _bllRequest.UpdateRequestStateAsync(new List<UpdateStateDto> { dto }).GetAwaiter().GetResult();
                }
                else if (eventValue == HL7Helper.UpdateExamState)//JH0405
                {
                    _logger.LogInformation("进行的操作是：消息代码--JH0405，更新检查状态");
                    var dtoList = HL7Helper.CreateUpdateExamStateDto(element);
                    _bllRequest.UpdateRequestStateAsync(dtoList).GetAwaiter().GetResult();
                }
                else
                {
                    _logger.LogInformation($"预约只处理《JH0201》,《JH0204》,《JH0405》，不处理-事件类型：{eventValue}");
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                _logger.LogError("异常：" + ex);
            }
            var result = HL7Helper.CreateReturnXml(eventValue, error);
            return result;
        }
    }
}
